package postgres

import (
	"context"
	"quipus/internal/database/model"
	apb "quipus/proto/gen/assist"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
	"github.com/pkg/errors"
)

func (p *PGDB) GetLLMProvider(ctx context.Context, providerId int32) (*model.LlmProvider, error) {
	p.query()
	qdo := q.WithContext(ctx)
	provider := qdo.LlmProvider

	return provider.Where(q.LlmProvider.ID.Eq(providerId)).First()
}

func (p *PGDB) CreateLLMProvider(ctx context.Context, create *model.LlmProvider) error {
	p.query()
	qdo := q.WithContext(ctx)
	err := qdo.LlmProvider.Create(create)
	if err != nil {
		return errors.Wrap(err, "failed to create llm provider")
	}
	return nil
}

func (p *PGDB) DeleteLLMProvider(ctx context.Context, providerId int32) error {
	p.query()
	provider := q.WithContext(ctx).LlmProvider
	_, err := provider.Where(q.LlmProvider.ID.Eq(providerId)).Delete()
	if err != nil {
		return errors.Wrap(err, "failed to delete provider")
	}
	return nil
}

func (p *PGDB) UpdateLLMProvider(ctx context.Context, update *apb.UpdateLLMProvider) (*model.LlmProvider, error) {
	p.query()
	qdo := q.WithContext(ctx)
	if update.Id < 0 {
		return nil, errors.New("id is required")
	}

	provider := qdo.LlmProvider
	provider = provider.Where(q.LlmProvider.ID.Eq(update.Id))

	updateValue := &model.LlmProvider{}
	updateValue.ID = update.Id
	if update.UpdatedTs > 0 {
		updateValue.UpdatedTs = update.UpdatedTs
	}

	if update.Name != "" {
		updateValue.Name = update.Name
	}

	if update.Api != "" {
		updateValue.APIName = update.Api
	}

	if update.Url != "" {
		updateValue.AccessURL = update.Url
	}

	if update.AuthInfo != "" {
		updateValue.AuthInfo = update.AuthInfo
	}

	if len(update.Description) > 0 {
		updateValue.Description = update.Description
	}

	_, e := provider.Updates(updateValue)

	return updateValue, e
}

func (p *PGDB) ListLLMProviders(ctx context.Context, find *apb.FindLLMProvider) ([]*model.LlmProvider, int32, error) {
	p.query()
	qdo := q.WithContext(ctx)
	provider := qdo.LlmProvider
	if find.Id > 0 {
		provider = provider.Where(q.LlmProvider.ID.Eq(find.Id))
	}
	if len(find.Api) > 0 {
		provider = provider.Where(q.LlmProvider.APIName.Eq(find.Api))
	}
	if len(find.Name) > 0 {
		provider = provider.Where(q.LlmProvider.Name.Eq(find.Name))
	}

	if find.TenantId > 0 {
		provider = provider.Where(q.LlmProvider.TenantID.Eq(find.TenantId))
	}

	limit := find.Limit
	if limit == 0 {
		limit = 10
	}

	ps, c, e := provider.FindByPage(int(find.Offset), int(limit))

	return ps, int32(c), e
}
